# -*- coding: utf-8 -*-
"""
Author:卢良策
E-mail:luliangce@gmail.com
Created:2018/3/31
Update:
账号部分相关操作
1.注册
2.登录
3.保存登录session
"""
from __future__ import unicode_literals

import json
import pickle

import requests

from Abstract import Base
from setting import logger


class Account(Base):
    """ 继承Base
        处理账号注册
    """

    def signUp(self, username="", password="", email="", firstname="", phone="", code=""):
        url = 'https://www.instagram.com/accounts/web_create_ajax/'
        param = dict(
            password=password,
            username=username,
            first_name=firstname
        )
        if phone:
            param["client_id"] = self.cMid
            param['seamless_login_enabled'] = '1'
            param["phone_number"] = phone
            param["sms_code"] = code
        else:
            param["email"] = email
        resp = self.post(url, data=param)
        try:
            response = json.loads(resp.content)
        except Exception as e:
            return False
        if response.get("account_created"):
            logger.debug(response)
            self.user_id = str(response.get("id"))
            return True

    def attemp(self, username="", password="", email="", firstname=""):
        """可选方法,注册时自动检测当前输入的内容是否可用

        Keyword Arguments:
            username {str} -- [用户名] (default: {""})
            password {str} -- [密码] (default: {""})
            email {str} -- [email] (default: {""})
            firstname {str} -- [姓名] (default: {""})

        Returns:
            [bool] -- [是否可用,可以使用为True]
        """

        url = "https://www.instagram.com/accounts/web_create_ajax/attempt/"
        param = dict(
            username=username,
            password=password,
            email=email,
            first_name=firstname
        )
        resp = self.post(url, data=param)
        try:
            j = resp.json()
            if j.get("account_created") == False:
                return True

        except:
            pass
        return False

    def smsSignUp(self, username="", password="", firstname="", phone=""):
        """短信注册

        Keyword Arguments:
            username {str} -- [用户名] (default: {""})
            password {str} -- [密码] (default: {""})
            firstname {str} -- [全名] (default: {""})
            phone {str} -- [手机号码] (default: {""})

        Returns:
            [bool] -- [是否注册成功]
        """

        if self.sendSms(phone):
            code = self.__getcode(phone)
            return self.signUp(username=username, password=password,
                               firstname=firstname, phone=phone, code=code)
        else:
            return False

    def sendSms(self, phone):
        """发送短信验证码

        Arguments:
            phone {[str]} -- [手机号码]

        Returns:
            [bool] -- [是否发送成功]
        """

        url = "https://www.instagram.com/accounts/send_signup_sms_code_ajax/"
        client_id = self.cMid
        param = {
            "phone_number": phone,
            "client_id": client_id
        }
        logger.info("向{}发送验证码".format(phone))
        resp = self.post(url, data=param)
        #{"sms_sent": true, "status": "ok"}
        try:

            return resp.json().get("sms_sent")
        except:
            return False

    def __getcode(self, phone=""):
        """获取手机收到的短信验证码
           目前为手动输入,可替换修改为其他方式
        Arguments:
            phone {str} -- 手机号码
        Returns:
            [str] -- [验证码]
        """

        code = input("sms:")
        return code


def main():
    a = Account()
    r = a.smsSignUp(username="liangce233", password="cdasdas",
                firstname="bilibili2233", phone="+8618698587693")
    # print r

if __name__ == '__main__':
    main()
